package cn.tedu.sp03.user.service;

import cn.tedu.sp01.pojo.User;
import cn.tedu.sp01.service.UserService;
import cn.tedu.web.util.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
@RefreshScope  //有了这个注解，刷新到的新配置才会重新注入到对象中
public class UserServiceImpl implements UserService {

    @Value("${sp.user-service.users}")
    private String userJson;

    @Override
    public User getUser(Integer userId) {
        log.info("users json string"+userJson);
        //传统的转class
        /*List<User> lists = new ArrayList<>();
        List<User> list = JsonUtil.from(userJson, lists.getClass());*/

        //userJson -> List<User>
        //Jackson API 利用匿名内部类继承语法
        List<User> list = JsonUtil.from(userJson, new TypeReference<List<User>>() {});
        for (User u:list){
            if (u.getId().equals(userId)){
                return u;
            }
        }

        return new User(userId,"用户名"+userId,"密码"+userId);
    }

    @Override
    public void addScore(Integer userId, Integer score) {

        log.info("user"+userId+"- 增加积分"+score);
    }
}
